package com.na.report.core.action;

import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.Base64;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.na.report.Action;
import com.na.report.Application;
import com.na.report.core.NetTrafficInfo;
import com.na.report.db.NetTraffic;
import com.na.report.db.NetTrafficMapper;
import com.na.report.utils.ByteArrayStream;
import com.na.report.utils.CommonUtils;
import com.na.report.utils.IOUtils;

public class GameNetTrafficReportAction implements Action {

	static final AtomicInteger POOL_ID = new AtomicInteger();
	static final Executor EXE = Executors.newFixedThreadPool(5, new ThreadFactory() {
		@Override
		public Thread newThread(Runnable r) {
			Thread t = new Thread(r, "POOL-" + POOL_ID.getAndIncrement());
			t.setDaemon(true);
			return t;
		}
	});
	
	private static final Logger log = LoggerFactory.getLogger(GameNetTrafficReportAction.class);
	
	@Override
	public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
		GZIPInputStream gzip = null;
		try {
			String data = req.getParameter("data");
			byte[] bytes = Base64.getUrlDecoder().decode(data.getBytes(IOUtils.UTF8));
			gzip = new GZIPInputStream(new ByteArrayInputStream(bytes));
			ByteArrayStream buf = new ByteArrayStream(1024);
			while (buf.write(gzip, 512) != -1) {
			}
			String json = buf.toString(IOUtils.UTF8);
			final String ip = CommonUtils.getRequestAddr(req);
			final NetTrafficInfo info = JSONObject.parseObject(json, NetTrafficInfo.class);
			EXE.execute(new Runnable() {
				@Override
				public void run() {
					NetTraffic[] entities = info.toEntities(ip);
					Arrays.sort(entities);
					SqlSession session = null;
					try {
						session = Application.getDBFactory().openSession();
						NetTrafficMapper mapper = session.getMapper(NetTrafficMapper.class);
						for (NetTraffic e : entities) {
							mapper.save(e);
						}
						log.info("[SAVE GAME NET TRAFFIC]SUCC");
					} catch (Exception e) {
						log.error("[SAVE GAME NET TRAFFIC]ERROR", e);
					} finally {
						if (session != null) {
							session.commit();
							session.close();
						}
					}
				}
			});
			res.getWriter().println("ok");
			IOUtils.closeQuietly(buf);
		} catch (Exception e) {
			throw e;
		} finally {
			IOUtils.closeQuietly(gzip);
		}
	}

}
